package cn.kiliter.web.servlet;

import cn.kiliter.excation.UserException;
import cn.kiliter.model.User;
import cn.kiliter.serviece.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@WebServlet("/register")
public class registerServlet extends HttpServlet {
    private UserService service=new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String checkcode = request.getParameter("checkcode");
        Object checkcode_session = request.getSession().getAttribute("checkcode_session");
        if(!checkcode_session.equals(checkcode)&&"".equals(checkcode)){
           request.setAttribute("checkcode_err","checkerror");
           request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }


        try {
            User user=new User();
            BeanUtils.populate(user,request.getParameterMap());
            user.setActiveCode(UUID.randomUUID().toString());
            user.setRole("普通用户");
            user.setRegistTime(new Date());
            service.register(user);
            request.getRequestDispatcher("/registersuccess.jsp").forward(request,response);
        }  catch (UserException e) {
            e.printStackTrace();
            request.setAttribute("register_err",e.getMessage());
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
